<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
    <link rel="stylesheet" href="lib/css/bootstrap.css">
    <script src="lib/js/vue.js" type="text/javascript" charset="utf-8"></script>


</head>
<body>
<div id="app">
    <pinglun @shuaxin="loadComponents"></pinglun>
    <ul class="list-group">
        <li class="list-group-item" v-for="item in list" :key="item.id">
            <span class="badge">评论人： {{item.user}}</span>
            {{item.content}}
        </li>
    </ul>
    <!-- 评论列表结束 -->
</div>

<template id="temp1">
    <div>
        <div class="form-group">
            <label>评论人：</label>
            <input type="text" class="form-control" v-model="user">
        </div>
        <div class="form-group">
            <label>评论内容：</label>
            <textarea class="form-control" v-model="content"></textarea>
        </div>
        <div class="form-group">
            <input type="button" class="btn btn-primary" value="发表评论" @click="postComment">
        </div>
    </div>

</template>

<script>
    // 创建一个vue实例
    new Vue({
        el:'#app',
        data:{
           list:[
               {id: Date.now(),user:'李白',content:'天生我材必有用'},
               {id: Date.now(),user:'李白2',content:'天生我材必有用'},
               {id: Date.now(),user:'李白3',content:'天生我材必有用'}
           ]
        },
        created(){
            this.loadComponents()

        },
        methods:{
            loadComponents() {
                var list = JSON.parse(localStorage.getItem('cmts' || '[]'))
                this.list = list
            }

        },
        components:{
            pinglun:{
                template:'#temp1',
                data() {
                    return{
                        user:'',
                        content:''
                    }
                },
                methods:{
                    postComment() {
                        var comment = {id: Date.now(), user: this.user, content: this.content}
                        var list = JSON.parse(localStorage.getItem('cmts' || '[]'))
                        list.unshift(comment)
                        localStorage.setItem('cmts', JSON.stringify(list))
                        this.user = this.content = ''
                        this.$emit('shuaxin')
                    }
                }
            }
        }
    })
</script>
</body>
</html>
